<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
  </head>

  <body>
    <input type="text" id="username" /> <input type="checkbox" name="" id="remember" /> 记住用户名
    <script>
      // 获取对象的标签对象
      var username = document.querySelector("#username");
      var remember = document.querySelector("#remember");

      // 判断本地存储中是否存储了 key为username的数据 如果存储 就将数据取出来 显示在输入框中并且将复选框打上勾
      if (window.localStorage.getItem("username")) {
        username.value = window.localStorage.getItem("username");
        remember.checked = true;
      }

      // 如果需要记住用户名 就将输入框的数据存储到本地存储中 如果不想记住就将本地存储中对应的数据删除
      remember.addEventListener("change", function () {
        if (this.checked) {
          if (username.value.trim().length != 0) window.localStorage.setItem("username", username.value);
        } else {
          // 将本地存储的数据删除
          window.localStorage.removeItem("username");
        }
      });
    </script>
  </body>
</html>
